package com.zyz.zchat;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import java.io.*;
import java.net.*;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Chat {
    InetAddress dest;
    Socket peer;
    ObservableList<Message> allMessages;
    Queue<Message>messageBuf;
    static ExecutorService sendService;
    {
        sendService= Executors.newSingleThreadExecutor();
    }

    Chat(InetAddress dest) throws IOException {
        allMessages= FXCollections.observableList(new LinkedList<>());
        messageBuf=new LinkedList<>();
        this.dest=dest;
        peer =new Socket();

    }

    @Override
    public String toString() {
        return "Chat{" +
                "dest=" + dest +
                ", peer=" + peer +
                ", allMessages=" + allMessages +
                '}';
    }

    void sendMessage(String message)
    {
        Message wrappedMessage= null;
        try {
            wrappedMessage = Message.getNowMessage(message, InetAddress.getLocalHost(),dest);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sendMessage(wrappedMessage);
    }
    synchronized void sendMessage(Message message)
    {
        sendService.execute(()->{
            try {
                peer=new Socket();
                peer.connect(new InetSocketAddress(dest.getHostName(),ChatManager.listenPort));
                ObjectOutputStream out= new ObjectOutputStream(peer.getOutputStream());
                out.writeObject(message);
                allMessages.add(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    void receiveMessage(Message m)
    {
        allMessages.add(m);
    }
}
class Message implements java.io.Serializable
{

    LocalDate date;
    LocalTime time;
    String content;
    InetAddress sender;
    InetAddress receiver;
    public Message(LocalDate date,LocalTime time,String content,InetAddress sender,InetAddress receiver)
    {
        this.content=content;
        this.time=time;
        this.date=date;
        this.sender=sender;
        this.receiver=receiver;
    }
    public static Message getNowMessage(String content,InetAddress sender,InetAddress receiver)
    {
        return new Message(LocalDate.now(),LocalTime.now(),content,sender,receiver);
    }

    @Override
    public String toString() {
        return
                date +
                " " + time +
                "\n来自：" + sender +
                "\n发给：" + receiver +
                        "\n" + content;
    }
}
